import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import router from '@/router'

//请求拦截器
axios.interceptors.request.use(config => {
  //如果存在token，请求携带这个token
  if (sessionStorage.getItem("tokenStr")) {
    config.headers['Authorization'] = sessionStorage.getItem("tokenStr")
  }
  return config
})

//响应拦截器
axios.interceptors.response.use(success => {
  if (success.status && success.status == 200) {
    //业务逻辑错误
    if (success.data.code == 500 || success.data.code == 403) {
      Message.error({ message: success.data.message })
      return
    } else if (success.data.code == 401) { //token过期
      MessageBox.confirm(success.data.message, '系统提示', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (sessionStorage.getItem('user')) {
          sessionStorage.removeItem('user')
          router.replace('/login')
        } else {
          router.replace('/login')
        }
      })
    }
    if (success.data.message) {
      if (success.data.message == '暂未登录或token已过期') {
      } else {
        Message.success({ message: success.data.message })
      }
    }
  }
  return success.data
}, error => {
  if (error.response.code == 504 || error.response.code == 404) {
    Message.error({ message: '服务器异常' })
  } else if (error.response.code == 403) {
    Message.error({ message: '权限不足，请联系管理员！' })
  } else if (error.response.code == 401) {
    Message.error({ message: '尚未登陆，请先登录！' })
    router.replace('/login')
  } else {
    if (error.response.data.message) {
      Message.error({ message: error.response.data.message })
    } else {
      Message.error({ message: '未知错误' })
    }
  }
  return
})

export const $post = (url, param) => {
  return axios.post(url, param)
}

export const $get = (url) => {
  return axios.get(url)
}

export const $put = (url, param) => {
  return axios.put(url, param)
}

export const $delete = (url) => {
  return axios.delete(url)
}